package com.ruoyi.web.controller.system;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.ruoyi.common.config.CosConfig;
import com.ruoyi.common.config.lphCosConfig;
import com.ruoyi.system.domain.Book;
import com.ruoyi.system.domain.PageIng;
import com.ruoyi.system.domain.ZhyCollect;
import com.ruoyi.system.service.PageIngService;
import com.ruoyi.system.service.ZhyCollectService;
import com.ruoyi.web.controller.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/api")
public class PageIngController {
      static String bucket = "lph-1313472936";
      @Autowired
      private ZhyCollectService zhyCollectService;
      @Autowired
    private PageIngService pageIngService;
//    @RequestMapping("/pageIng/down")
//    public  String down(@RequestParam("shipin") MultipartFile shipin1,@RequestParam("userid") int userid,@RequestParam("classify") int classify, @RequestParam("classifyname") int classifyname, @RequestParam("name") String name1)
//    {
//        System.out.println("进入controller");
//        String tmpFilePath = "D://img"  ;
//        File tmp = new File(tmpFilePath);
//        //原始文件名 //获取文件名
//        String originalFilename = shipin1.getOriginalFilename();//abc.jpg
//        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
//        //没有路径就创建路径
//       if (!tmp.exists()) {
//            tmp.mkdirs();
//        }
//        String name=null;
//        if(classify==1) {
//             name = "前端"+name1 + suffix;
//        }else if(classify==2){
//            name="后端"+name1+suffix;
//        }else {
//            name="全栈"+name1+suffix;
//        }
//        System.out.println(name);
//        String shipin = tmpFilePath+ "//" + name;
//        Date date=new Date();
//        System.out.println(date);
//        PageIng pageIng = new PageIng();
////        String s=UUID.randomUUID().toString().substring((UUID.randomUUID().toString()).lastIndexOf("-")+1);//c74ae079b0ee
////         pageIng.setId(s);
//         pageIng.setUserid(userid);
//         //fileName.substring(0,fileName.lastIndexOf(".")) 去掉.后缀
//         pageIng.setName(name.substring(0,name.lastIndexOf(".")));
//         pageIng.setClassify(classify);
//         pageIng.setClassifyname(classifyname);
//         pageIng.setStatus(0);
//         pageIng.setShipin(shipin);
//        pageingMapper.add(pageIng);
//        System.out.println(shipin);
//        File upFile = new File(shipin);
//        try {
//            shipin1.transferTo(upFile);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return "ok";
//    }
@RequestMapping("/pageIng/{pageNum}")//查询全部status=1
public R<List<PageIng>> select(@PathVariable("pageNum") Integer pageNum)
{
    PageHelper.startPage(pageNum,6);
    List<PageIng> select = pageIngService.select();
    PageInfo<PageIng> pageInfo= new PageInfo<>(select);
    return R.success(select.size(),select);
}

    @RequestMapping("/pageIng/update")//更改状态
  public R<String> updateStatus(@RequestBody PageIng pageIng)
    {        if(pageIng.getStatus()==0)
                 pageIngService.updateStatus1(pageIng.getId());
             else
                 pageIngService.updateStatus0(pageIng.getId());
        return  R.success(1,"状态更改成功");
    }
    @PostMapping("/pageIng/selectName/{pageNum}")//通过名字查询
    public R <List<PageIng>> selectName(@PathVariable("pageNum") Integer pageNum,@RequestBody PageIng pageIng)
    {
        PageHelper.startPage(pageNum,6);
        List<PageIng> selectname = pageIngService.selectname(pageIng.getName());
        PageInfo<PageIng> pageInfo= new PageInfo<>(selectname);
           return  R.success(selectname.size(),selectname);
    }
    @RequestMapping("/pageIng/selecUsertId/{pageNum}")//查询用户查询自己全部
    public R<List<PageIng>> selectUserid(@PathVariable Integer pageNum,@RequestBody PageIng pageIng)
    {
        PageHelper.startPage(pageNum,6);
        List<PageIng> pageIngs = pageIngService.selectUserId(pageIng.getUserid());
        PageInfo<PageIng> pageInfo= new PageInfo<>(pageIngs);
        return R.success(pageIngs.size(),pageIngs);
    }
    @RequestMapping("/pageIng/selectUserId/{userid}")//查询用户查询自己全部
    public R<List<PageIng>> selectUserids(@PathVariable("userid") Integer userid)
    {

        List<PageIng> pageIngs = pageIngService.selectUserId(userid);
        return R.success(pageIngs.size(),pageIngs);
    }
        @RequestMapping("/pageIng/selectByid")
    public R<PageIng> selectId(@RequestBody PageIng pageIng)
    {
        PageIng pageIng1 = pageIngService.selectByid(pageIng.getId());
        pageIng1.setLook(pageIng1.getLook()+1);
        pageIngService.look(pageIng1);
        return  R.success(1,pageIng1);
    }
    @PostMapping("/down")//上传
    public String downup(@RequestParam("file") MultipartFile shipin,@RequestParam("userid") int userid,@RequestParam("username") String username,@RequestParam("classify") int classify,@RequestParam("status") int status,@RequestParam("classifyname")int classifyname ,@RequestParam("name") String name){
  //  public String downup(@RequestBody PageIng pageIng){
        //        COSCredentials cred = new BasicCOSCredentials(accessKeyId,SecretKey);
//        ClientConfig clientConfig = new ClientConfig(new Region(endpoint));
//        COSClient cosClient = new COSClient(cred, clientConfig);
        COSClient cosClient = new lphCosConfig().cosClient();
        //原始文件名 //获取文件名
        String url = null;
        String originalFilename = shipin.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newfilename=UUID.randomUUID().toString()+suffix;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
         // 上传的流如果能够获取准确的流长度，则推荐一定填写 content-length
         // 如果确实没办法获取到，则下面这行可以省略，但同时高级接口也没办法使用分块上传了
            InputStream inputStream = shipin.getInputStream();
            objectMetadata.setContentLength(inputStream.available());
            PutObjectRequest putObjectRequest1 = new PutObjectRequest(new lphCosConfig().getbucket(),newfilename, inputStream, objectMetadata);
            cosClient.putObject(putObjectRequest1);
            url ="https://" + new lphCosConfig().getbucket() + ".cos.ap-guangzhou.myqcloud.com" + "/" + newfilename;
            PageIng pageIng = new PageIng();
            pageIng.setUserid(userid);
            pageIng.setUsername(username);
            pageIng.setStatus(status);
            pageIng.setClassify(classify);
            pageIng.setClassifyname(classifyname);
            pageIng.setName(name);
            pageIng.setShipin(url);
              pageIngService.add(pageIng);
        } catch (CosClientException | IOException e) {
            e.printStackTrace();
            return "上传失败";
        } finally {
            cosClient.shutdown();
        }
        return "上传成功";
    }
    @RequestMapping("/pageIng/selectByclassify")
   // public List<PageIng> selectByclassify(@RequestParam("userid") int userid ,@RequestParam("classify") int classify,@RequestParam("classifyname")int classifyname)
    public R<List<PageIng>> selectByclassify(@RequestBody PageIng pageIng)//查分类
    {
        List<PageIng> pageIngs = pageIngService.selectByclassify(pageIng.getClassify(),pageIng.getClassifyname());
        return R.success(pageIngs.size(),pageIngs);
    }
    @RequestMapping("/pageIng/userid/selectByclassify")//查询用户自己的分类
    // public List<PageIng> selectByclassify(@RequestParam("userid") int userid ,@RequestParam("classify") int classify,@RequestParam("classifyname")int classifyname)
    public R<List<PageIng>> selectUseridByclassify(@RequestBody PageIng pageIng)
    {
        List<PageIng> pageIngs = pageIngService.selectByUseridclassify(pageIng.getUserid(),pageIng.getClassify(),pageIng.getClassifyname());
        return R.success(pageIngs.size(),pageIngs);
    }


    @RequestMapping("/pageIng/delete")
    //@RequestParam("id") int id
    public  R<String> delete(@RequestBody PageIng pageIng)
    {
//     COSCredentials cred = new BasicCOSCredentials(accessKeyId,SecretKey);
//        ClientConfig clientConfig = new ClientConfig(new Region(endpoint));
//        COSClient cosClient = new COSClient(cred, clientConfig);
        COSClient cosClient = new lphCosConfig().cosClient();
        PageIng pageIngs = pageIngService.selectByid(pageIng.getId());
        String key=(pageIngs.getShipin()).substring((pageIngs.getShipin()).lastIndexOf("/"));
        try {
            cosClient.deleteObject(new lphCosConfig().getbucket(),key);
            pageIngService.delete(pageIng.getId());
            ZhyCollect zhyCollect = new ZhyCollect();
            zhyCollect.setType("视频");
            zhyCollect.setId(pageIng.getId());
            zhyCollectService.deleteCollectById(zhyCollect);
            return R.success(1,"删除文件成功");
        } catch (CosClientException e) {
            return R.error("删除文件失败");
        } finally {
            cosClient.shutdown();
        }
    }
}
